import {
  PromptEngine,
  ChatMode,
  MemoryType,
  PromptTemplate,
  PromptSectionType,
  EnhancedPromptConfig
} from '../src';

/**
 * 提示词引擎使用示例
 * 展示如何使用新的提示词生成系统
 */

async function basicUsageExample() {
  console.log('=== 基本使用示例 ===');
  
  // 创建提示词引擎
  const promptEngine = new PromptEngine();

  // 构建简单的提示词
  const prompt = await promptEngine.buildPrompt(
    ChatMode.CHAT,
    'How do I implement a binary search algorithm?',
    {
      conversationHistory: [
        {
          id: '1',
          role: 'user',
          content: 'I need help with algorithms',
          timestamp: new Date(Date.now() - 60000)
        },
        {
          id: '2',
          role: 'assistant',
          content: 'I can help you with various algorithms. What specific algorithm are you interested in?',
          timestamp: new Date(Date.now() - 30000)
        }
      ]
    }
  );

  console.log('Generated prompt:');
  console.log(prompt);
}

async function advancedUsageExample() {
  console.log('\n=== 高级使用示例 ===');
  
  // 创建带配置的提示词引擎
  const config: EnhancedPromptConfig = {
    templateId: 'default-chat',
    maxContextLength: 10000,
    systemPrompt: ``,
    includeCodeContext: true,
    includeMemories: true,
    includeToolHistory: true,
    contextPriority: {
      codeContext: 0.9,
      memories: 0.8,
      toolHistory: 0.7,
      conversationHistory: 0.6,
      dynamicAdjustment: true
    },
    memoryRetrievalConfig: {
      maxMemories: 5,
      semanticThreshold: 0.4,
      timeDecayFactor: 0.02,
      scopeFiltering: true,
      relevanceScoring: true
    }
  };

  const promptEngine = new PromptEngine(config);

  // 添加记忆
  promptEngine.addMemory({
    id: 'mem1',
    content: 'User prefers Python for algorithm implementations',
    type: MemoryType.PREFERENCE,
    relevance: 0.8,
    timestamp: new Date(Date.now() - 86400000), // 1 day ago
    metadata: {
      scope: 'global',
      category: 'programming'
    }
  });

  promptEngine.addMemory({
    id: 'mem2',
    content: 'Binary search is an efficient algorithm for searching sorted arrays',
    type: MemoryType.FACT,
    relevance: 0.9,
    timestamp: new Date(Date.now() - 3600000), // 1 hour ago
    metadata: {
      scope: 'workspace',
      category: 'algorithms'
    }
  });

  // 添加工具使用历史
  promptEngine.addToolUsage({
    id: 'tool1',
    toolName: 'code-generator',
    input: { language: 'python', algorithm: 'quicksort' },
    output: { code: 'def quicksort(arr): ...', success: true },
    success: true,
    timestamp: new Date(Date.now() - 1800000), // 30 minutes ago
    duration: 2500,
    metadata: {
      context: {
        filePath: '/algorithms/sorting.py',
        chatMode: ChatMode.AGENT
      }
    }
  });

  // 构建带有完整上下文的提示词
  const prompt = await promptEngine.buildPrompt(
    ChatMode.AGENT,
    'Generate a Python implementation of binary search with comments',
    {
      codeContext: {
        currentFile: {
          path: '/algorithms/search.py',
          content: '# Search algorithms\n\ndef linear_search(arr, target):\n    for i, val in enumerate(arr):\n        if val == target:\n            return i\n    return -1',
          language: 'python',
          size: 150,
          lastModified: new Date()
        },
        selectedCode: 'def linear_search(arr, target):',
        workspaceFiles: [
          {
            path: '/algorithms/sorting.py',
            language: 'python',
            size: 500
          }
        ],
        gitInfo: {
          branch: 'feature/algorithms',
          commit: 'abc123',
          status: 'clean'
        }
      },
      config
    }
  );

  console.log('Generated advanced prompt:');
  console.log(prompt);
}

async function customTemplateExample() {
  console.log('\n=== 自定义模板示例 ===');
  
  const promptEngine = new PromptEngine();

  // 创建自定义模板
  const customTemplate: PromptTemplate = {
    id: 'code-review-template',
    name: 'Code Review Template',
    description: 'Template for code review tasks',
    mode: ChatMode.AGENT,
    systemPrompt: `You are an expert code reviewer. Analyze the provided code and give constructive feedback.

Focus on:
- Code quality and best practices
- Performance considerations
- Security issues
- Maintainability

User request: {{userMessage}}`,
    sections: [
      {
        id: 'code-to-review',
        name: 'Code to Review',
        type: PromptSectionType.CODE_CONTEXT,
        template: `## Code to Review

File: {{codeContext.currentFile.path}}
Language: {{codeContext.currentFile.language}}

\`\`\`{{codeContext.currentFile.language}}
{{codeContext.currentFile.content}}
\`\`\`

{{#if codeContext.selectedCode}}
Selected code for focused review:
\`\`\`{{codeContext.currentFile.language}}
{{codeContext.selectedCode}}
\`\`\`
{{/if}}`,
        enabled: true,
        priority: 95,
        conditions: [
          {
            type: 'context',
            field: 'codeContext.currentFile',
            operator: 'exists'
          }
        ]
      },
      {
        id: 'review-guidelines',
        name: 'Review Guidelines',
        type: PromptSectionType.GUIDELINES,
        template: `## Review Guidelines

{{#each guidelines}}
- {{title}}: {{content}}
{{/each}}`,
        enabled: true,
        priority: 80,
        conditions: [
          {
            type: 'context',
            field: 'guidelines',
            operator: 'exists'
          }
        ]
      }
    ],
    variables: {
      userMessage: {
        name: 'userMessage',
        type: 'string',
        description: 'User message',
        required: true
      }
    }
  };

  // 注册自定义模板
  promptEngine.registerTemplate(customTemplate);

  // 使用自定义模板
  const prompt = await promptEngine.buildPrompt(
    ChatMode.AGENT,
    'Please review this code for potential improvements',
    {
      codeContext: {
        currentFile: {
          path: '/src/utils.js',
          content: `function processData(data) {
    var result = [];
    for (var i = 0; i < data.length; i++) {
        if (data[i] != null) {
            result.push(data[i].toString().toUpperCase());
        }
    }
    return result;
}`,
          language: 'javascript',
          size: 200,
          lastModified: new Date()
        },
        selectedCode: 'for (var i = 0; i < data.length; i++)'
      },
      config: {
        templateId: 'code-review-template'
      }
    }
  );

  console.log('Generated code review prompt:');
  console.log(prompt);
}

async function statisticsExample() {
  console.log('\n=== 统计信息示例 ===');
  
  const promptEngine = new PromptEngine();

  // 添加一些测试数据
  for (let i = 0; i < 10; i++) {
    promptEngine.addMemory({
      id: `mem${i}`,
      content: `Test memory ${i}`,
      type: i % 2 === 0 ? MemoryType.FACT : MemoryType.PREFERENCE,
      relevance: Math.random(),
      timestamp: new Date(Date.now() - i * 3600000),
      metadata: {}
    });

    promptEngine.addToolUsage({
      id: `tool${i}`,
      toolName: i % 3 === 0 ? 'file-reader' : 'code-generator',
      input: { test: i },
      output: { result: `output${i}` },
      success: i % 4 !== 0,
      timestamp: new Date(Date.now() - i * 1800000),
      duration: Math.random() * 5000,
      metadata: {}
    });
  }

  // 获取统计信息
  const memoryStats = promptEngine.getMemoryStats();
  const toolStats = promptEngine.getToolStats();

  console.log('Memory Statistics:', memoryStats);
  console.log('Tool Statistics:', toolStats);
}

// 运行示例
async function runExamples() {
  try {
    await basicUsageExample();
    await advancedUsageExample();
    await customTemplateExample();
    await statisticsExample();
  } catch (error) {
    console.error('Error running examples:', error);
  }
}

// 如果直接运行此文件
if (require.main === module) {
  runExamples();
}

export {
  basicUsageExample,
  advancedUsageExample,
  customTemplateExample,
  statisticsExample,
  runExamples
};
